/*
### jQuery Multiple File Upload Plugin v1.44 - 2009-04-08 ###
* Home: http://www.fyneworks.com/jquery/multiple-file-upload/
* Code: http://code.google.com/p/jquery-multifile-plugin/
*
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
###
*/


;if (window.jQuery) (function($) {
    // plugin initialization
    $.fn.MultiFile = function(options) {
        if (this.length == 0) return this; // quick fail

        // Handle API methods
        if (typeof arguments[0] == 'string') {
            // Perform API methods on individual elements
            if (this.length > 1) {
                var args = arguments;
                return this.each(function() {
                    $.fn.MultiFile.apply($(this), args);
                });
            };
            // Invoke API method handler
            $.fn.MultiFile[arguments[0]].apply(this, $.makeArray(arguments).slice(1) || []);
            // Quick exit...
            return this;
        };

        // Initialize options for this call
        var options = $.extend(
			{},
			$.fn.MultiFile.options,
			options || {}
		);

        $('form').not('MultiFile-intercepted').addClass('MultiFile-intercepted').submit(function() {
            $.fn.MultiFile.disableEmpty;
        });

        if ($.fn.MultiFile.options.autoIntercept) {
            $.fn.MultiFile.intercept($.fn.MultiFile.options.autoIntercept /* array of methods to intercept */);
            $.fn.MultiFile.options.autoIntercept = null; /* only run this once */
        };

        // loop through each matched element
        this
		 .not('.MultiFile-applied')
			.addClass('MultiFile-applied')
		.each(function() {
		    window.MultiFile = (window.MultiFile || 0) + 1;
		    var group_count = window.MultiFile;

		    var MultiFile = { e: this, E: $(this), clone: $(this).clone() };

		    //# USE CONFIGURATION
		    if (typeof options == 'number') options = { max: options };
		    var o = $.extend({},
                $.fn.MultiFile.options,
                options || {},
   				($.metadata ? MultiFile.E.metadata() : ($.meta ? MultiFile.E.data() : null)) || {}, {}
            );

		    if (o.max <= 0) {
		        o.max = MultiFile.E.attr('maxlength');
		        if (o.max <= 0) {
		            o.max = (String(MultiFile.e.className.match(/\b(max|limit)\-([0-9]+)\b/gi) || ['']).match(/[0-9]+/gi) || [''])[0];
		            o.max = o.max <= 0 ? -1 : String(o.max).match(/[0-9]+/gi)[0];
		        }
		    };

		    o.max = new Number(o.max);
		    o.accept = o.accept || MultiFile.E.attr('accept') || '';
		    if (!o.accept) {
		        o.accept = (MultiFile.e.className.match(/\b(accept\-[\w\|]+)\b/gi)) || '';
		        o.accept = new String(o.accept).replace(/^(accept|ext)\-/i, '');
		    };

		    // APPLY CONFIGURATION
		    $.extend(MultiFile, o || {});
		    MultiFile.STRING = $.extend({}, $.fn.MultiFile.options.STRING, MultiFile.STRING);

		    // PRIVATE PROPERTIES/METHODS
		    $.extend(MultiFile, {
		        n: 0,
		        slaves: [],
		        files: [],
		        instanceKey: MultiFile.e.id || 'MultiFile' + String(group_count),
		        generateID: function(z) { return MultiFile.instanceKey + (z > 0 ? '_F' + String(z) : ''); },
		        trigger: function(event, element) {
		            var handler = MultiFile[event], value = $(element).attr('value');
		            if (handler) {
		                var returnValue = handler(element, value, MultiFile);
		                if (returnValue != null) return returnValue;
		            }
		            return true;
		        }
		    });

		    if (String(MultiFile.accept).length > 1) {
		        MultiFile.rxAccept = new RegExp('\\.(' + (MultiFile.accept ? MultiFile.accept : '') + ')$', 'gi');
		    };


		    // Create wrapper to hold our file list
		    MultiFile.wrapID = MultiFile.instanceKey + '_wrap';
		    MultiFile.E.wrap('<div class="MultiFile-wrap" id="' + MultiFile.wrapID + '"></div>');
		    MultiFile.wrapper = $('#' + MultiFile.wrapID + '');

		    // MultiFile MUST have a name - default: file1[], file2[], file3[]
		    MultiFile.e.name = MultiFile.e.name || 'file' + group_count + '[]';

		    MultiFile.list = $(MultiFile.list);



		    // Bind a new element
		    MultiFile.addSlave = function(slave, slave_count) {
		        MultiFile.n++;
		        slave.MultiFile = MultiFile;

		        if (slave_count > 0) {
		            slave.id = MultiFile.generateID(slave_count);
		        }

		        slave.name = String(MultiFile.namePattern
		        /*master name*/.replace(/\$name/gi, $(MultiFile.clone).attr('name'))
		        /*master id  */.replace(/\$id/gi, $(MultiFile.clone).attr('id'))
		        /*group count*/.replace(/\$g/gi, group_count)//(group_count>0?group_count:''))
		        /*slave count*/.replace(/\$i/gi, slave_count)//(slave_count>0?slave_count:''))
                );

		        // If we've reached maximum number, disable input slave
		        if ((MultiFile.max > 0) && ((MultiFile.n - 1) > (MultiFile.max))) {
		            // MultiFile.n Starts at 1, so subtract 1 to find true count
		            slave.disabled = true;
		        };

		        // Remember most recent slave
		        MultiFile.current = MultiFile.slaves[slave_count] = slave;

		        // We'll use jQuery from now on
		        slave = $(slave);

		        // Clear value
		        slave.val('').attr('value', '')[0].value = '';

		        // Stop plugin initializing on slaves
		        slave.addClass('MultiFile-applied');

		        // Triggered when a file is selected
		        slave.change(function() {
		            // Lose focus to stop IE7 firing onchange again
		            $(this).blur();

		            //# Trigger Event! onFileSelect
		            if (!MultiFile.trigger('onFileSelect', this, MultiFile)) {
		                return false;
		            }

		            //# Retrive value of selected file from element
		            var ERROR = '';
		            var v = String(this.value || '');

		            // check extension
		            if (MultiFile.accept && v && !v.match(MultiFile.rxAccept)) {
		                ERROR = MultiFile.STRING.denied.replace('$ext', String(v.match(/\.\w{1,4}$/gi)));
		            }

		            // Disallow duplicates
		            for (var f in MultiFile.slaves) {
		                if (MultiFile.slaves[f] && MultiFile.slaves[f] != this && MultiFile.slaves[f].value == v) {
		                    ERROR = MultiFile.STRING.duplicate.replace('$file', v.match(/[^\/\\]+$/gi));
		                }
		            }

		            // max length 50 characters
		            if (v.length > 0 && v.match(/[^\/\\]+$/gi).length > 0 && v.match(/[^\/\\]+$/gi)[0].length > 50) {
		                ERROR = MultiFile.STRING.maxlength;
		            }

		            // Create a new file input element
		            var newEle = $(MultiFile.clone).clone();
		            newEle.addClass('MultiFile');

		            // Handle error
		            if (ERROR != '') {
		                MultiFile.error(ERROR);
		                MultiFile.n--;
		                MultiFile.addSlave(newEle[0], slave_count);
		                slave.parent().prepend(newEle);
		                slave.remove();
		                return false;
		            };

		            // Hide this element (NB: display:none is evil!)
		            $(this).css({ position: 'absolute', top: '-3000px' });

		            // Add new element to the form
		            slave.after(newEle);

		            // Update list
		            MultiFile.addToList(this, slave_count);

		            // Bind functionality
		            MultiFile.addSlave(newEle[0], slave_count + 1);

		            //# Trigger Event! afterFileSelect
		            if (!MultiFile.trigger('afterFileSelect', this, MultiFile)) {
		                return false;
		            }

		        });

		        // Save control to element
		        $(slave).data('MultiFile', MultiFile);
		    };





		    // Add a new file to the list
		    MultiFile.addToList = function(slave, slave_count) {
		        //# Trigger Event! onFileAppend
		        if (!MultiFile.trigger('onFileAppend', slave, MultiFile)) {
		            return false;
		        }

		        var v = String(slave.value || '');
		        var a = $('<li title="' + MultiFile.STRING.selected.replace('$file', v) + '">' +
                        MultiFile.STRING.icon + ' ' +
                        MultiFile.STRING.file.replace('$file', v.match(/[^\/\\]+$/gi)[0]) +
                    '</li>');
		        var b = $('<a class="remove" title="remove" href="#' + MultiFile.wrapID + '">' + MultiFile.STRING.remove + '</a>');

		        MultiFile.list.append(
		            a.append(b)
		        );

		        b.click(function() {
		            //# Trigger Event! onFileRemove
		            if (!MultiFile.trigger('onFileRemove', slave, MultiFile)) {
		                return false;
		            }

		            MultiFile.n--;
		            MultiFile.current.disabled = false;

		            // Remove element, remove label, point to current
		            MultiFile.slaves[slave_count] = null;
		            $(slave).remove();
		            $(this).parent().remove();

		            // Show most current element again (move into view) and clear selection
		            $(MultiFile.current).css({ position: '', top: '' });
		            $(MultiFile.current).reset().val('').attr('value', '')[0].value = '';

		            //# Trigger Event! afterFileRemove
		            if (!MultiFile.trigger('afterFileRemove', slave, MultiFile)) {
		                return false;
		            }

		            return false;
		        });

		        //# Trigger Event! afterFileAppend
		        if (!MultiFile.trigger('afterFileAppend', slave, MultiFile)) {
		            return false;
		        }
		    };




		    /*----------------------------------------------------------------
		    *  ------> BEGIN CUSTOM MIDORI CODE (HANDLE EXISTING ATTACHMENTS)
		    *--------------------------------------------------------------*/
		    MultiFile.list.find('li').each(function(i) {
		        var a = $('<li title="' + $(this).attr('title') + '" name="' + $(this).text() + '" existing="existing">' +
		                MultiFile.STRING.icon + ' ' + $(this).text() +
		            '</li>');
		        var b = $('<a class="remove" title="remove" href="javascript:">' + MultiFile.STRING.remove + '</a>');

		        if ($(this).attr('readonly') == 'readonly') {
		            var title = $(this).attr('title');
		            var onclick = 'return DispEx(this,event,\'TRUE\',\'FALSE\',\'FALSE\',\'SharePoint.OpenDocuments.3\',\'0\',\'SharePoint.OpenDocuments\',\'\',\'\',\'1071741823\',\'\',\'0\',\'0\',\'0x7fffffffffffffff\')';

		            if ($(this).attr('disabled') == 'disabled')
		                title = '';

		            if ($(this).attr('canEdit') == 'canEdit')
		                onclick = 'return DispEx(this,event,\'TRUE\',\'FALSE\',\'FALSE\',\'SharePoint.OpenDocuments.3\',\'0\',\'SharePoint.OpenDocuments\',\'\',\'\',\'\',\'\',\'1\',\'0\',\'0x7fffffffffffffff\')';

		            a.html('<a title="' + title + '" href="' + title + '" ' +
	                    'onclick="' + onclick + '">' +
	                        MultiFile.STRING.icon + ' ' + $(this).text() +
	                    '</a>');
		        }
		        else if ($(this).attr('isProfilePicture') == 'isProfilePicture') {
		            a = $('<li title="' + $(this).attr('title') + '" name="' + $(this).text() + '" existing="existing">' +
		                '<img src="' + $(this).attr('title') + '" alt="' + $(this).attr('title') + '" class="' + $(this).attr('imageClass') + '"/>' +
		            '</li>');
		        }

		        MultiFile.list.append(a);
		        MultiFile.n++;

		        if ($(this).attr('readonly') != 'readonly') {
		            a.append(b);
		            b.click(function() {
		                var d = $(this).parents('#my_attachments').find('.deleted_attachments');
		                var v = $(d).val();
		                d.val(v + $(this).parent().attr('name') + '|');
		                $(this).parent().remove();
		                MultiFile.n--;
		                MultiFile.current.disabled = MultiFile.max > 0 && MultiFile.n - 1 > MultiFile.max;
		            });
		        }

		        $(this).remove();
		    });
		    /*----------------------------------------------------------------
		    *  --------> END CUSTOM MIDORI CODE (HANDLE EXISTING ATTACHMENTS)
		    *--------------------------------------------------------------*/

		    if (MultiFile.e.tagName != 'DIV') {
		        // Bind functionality to the first element
		        if (!MultiFile.MultiFile) {
		            MultiFile.addSlave(MultiFile.e, 0);
		        }

		        // Increment control count
		        MultiFile.n++;

		        MultiFile.current.disabled = MultiFile.max > 0 && MultiFile.n - 1 > MultiFile.max;

		        // Save control to element
		        MultiFile.E.data('MultiFile', MultiFile);
		    }
		});
    };

    /*--------------------------------------------------------*/

    /*
    ### Core functionality and API ###
    */
    $.extend($.fn.MultiFile, {
        /**
        * This method removes all selected files
        *
        * Returns a jQuery collection of all affected elements.
        *
        * @name reset
        * @type jQuery
        * @cat Plugins/MultiFile
        * @author Diego A. (http://www.fyneworks.com/)
        *
        * @example $.fn.MultiFile.reset();
        */
        reset: function() {
            var settings = $(this).data('MultiFile');
            //if(settings) settings.wrapper.find('a.MultiFile-remove').click();
            if (settings) settings.list.find('a.MultiFile-remove').click();
            return $(this);
        },


        /**
        * This utility makes it easy to disable all 'empty' file elements in the document before submitting a form.
        * It marks the affected elements so they can be easily re-enabled after the form submission or validation.
        *
        * Returns a jQuery collection of all affected elements.
        *
        * @name disableEmpty
        * @type jQuery
        * @cat Plugins/MultiFile
        * @author Diego A. (http://www.fyneworks.com/)
        *
        * @example $.fn.MultiFile.disableEmpty();
        * @param String class (optional) A string specifying a class to be applied to all affected elements - Default: 'mfD'.
        */
        disableEmpty: function(klass) {
            klass = String(klass || 'mfD');
            var o = [];
            $('input:file').each(function() { if ($(this).val() == '') o[o.length] = this; });
            return $(o).each(function() { this.disabled = true }).addClass(klass);
        },


        /**
        * This method re-enables 'empty' file elements that were disabled (and marked) with the $.fn.MultiFile.disableEmpty method.
        *
        * Returns a jQuery collection of all affected elements.
        *
        * @name reEnableEmpty
        * @type jQuery
        * @cat Plugins/MultiFile
        * @author Diego A. (http://www.fyneworks.com/)
        *
        * @example $.fn.MultiFile.reEnableEmpty();
        * @param String klass (optional) A string specifying the class that was used to mark affected elements - Default: 'mfD'.
        */
        reEnableEmpty: function(klass) {
            klass = String(klass || 'mfD');
            return $('input:file.' + klass).removeClass(klass).each(function() { this.disabled = false });
        },


        /**
        * This method will intercept other jQuery plugins and disable empty file input elements prior to form submission
        *
        * @name intercept
        * @cat Plugins/MultiFile
        * @author Diego A. (http://www.fyneworks.com/)
        *
        * @example $.fn.MultiFile.intercept();
        * @param Array methods (optional) Array of method names to be intercepted
        */
        intercepted: {},
        intercept: function(methods, context, args) {
            var method, value; args = args || [];
            if (args.constructor.toString().indexOf("Array") < 0) args = [args];
            if (typeof (methods) == 'function') {
                $.fn.MultiFile.disableEmpty();
                value = methods.apply(context || window, args);
                $.fn.MultiFile.reEnableEmpty();
                return value;
            };
            if (methods.constructor.toString().indexOf("Array") < 0) methods = [methods];
            for (var i = 0; i < methods.length; i++) {
                method = methods[i] + ''; // make sure that we have a STRING
                if (method) (function(method) { // make sure that method is ISOLATED for the interception
                    $.fn.MultiFile.intercepted[method] = $.fn[method] || function() { };
                    $.fn[method] = function() {
                        $.fn.MultiFile.disableEmpty();
                        value = $.fn.MultiFile.intercepted[method].apply(this, arguments);
                        $.fn.MultiFile.reEnableEmpty();
                        return value;
                    }; // interception
                })(method); // MAKE SURE THAT method IS ISOLATED for the interception
            }; // for each method
        }
    });

    /*--------------------------------------------------------*/

    /*
    ### Default Settings ###
    eg.: You can override default control like this:
    $.fn.MultiFile.options.accept = 'gif|jpg';
    */
    $.fn.MultiFile.options = { //$.extend($.fn.MultiFile, { options: {
        accept: '', // accepted file extensions
        max: -1,    // maximum number of selectable files

        // name to use for newly created elements
        namePattern: '$name', // same name by default (which creates an array)

        // STRING: collection lets you show messages in different languages
        STRING: {
            icon: '',
            remove: 'Remove',
            denied: 'You cannot select a $ext file.\nTry again...',
            maxlength: 'The file name cannot be longer than 50 characters',
            file: '$file',
            selected: 'File selected: $file',
            duplicate: 'This file has already been selected:\n$file',
            overwrite: 'This file already exists on the server:\n$file\n\nClick OK to overwrite the file on the server'
        },

        // name of methods that should be automcatically intercepted so the plugin can disable
        // extra file elements that are empty before execution and automatically re-enable them afterwards
        autoIntercept: ['submit', 'ajaxSubmit', 'validate' /* array of methods to intercept */],

        // error handling function
        error: function(s) {
            /*
            ERROR! blockUI is not currently working in IE
            if($.blockUI){
            $.blockUI({
            message: s.replace(/\n/gi,'<br/>'),
            css: { 
            border:'none', padding:'15px', size:'12.0pt',
            backgroundColor:'#900', color:'#fff',
            opacity:'.8','-webkit-border-radius': '10px','-moz-border-radius': '10px'
            }
            });
            window.setTimeout($.unblockUI, 2000);
            }
            else//{// save a byte!
            */
            alert(s);
            //}// save a byte!
        },

        ask: function(s) {
            return confirm(s);
        },

        //list: '#my_attachments ul.attachments'

        //list: '$("ul.attachments", $(this).parents(".MultiFile-wrap"))'
        list: 'ul.attachments'

    }; //} });

    /*--------------------------------------------------------*/

    /*
    ### Additional Methods ###
    Required functionality outside the plugin's scope
    */

    // Native input reset method - because this alone doesn't always work: $(element).val('').attr('value', '')[0].value = '';
    $.fn.reset = function() { return this.each(function() { try { this.reset(); } catch (e) { } }); };

    /*--------------------------------------------------------*/

    /*
    ### Default implementation ###
    The plugin will attach itself to file inputs
    with the class 'multi' when the page loads
    */
    $(function() {
        //$("input:file.multi").MultiFile();
        $("input[type=file].multi").MultiFile();
    });



    /*# AVOID COLLISIONS #*/
})(jQuery);
/*# AVOID COLLISIONS #*/
